package view.grammardevelopment.editsemantics;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;

import view.grammardevelopment.ComponentPanel;
import view.grammardevelopment.DisplayScreen;
import view.grammardevelopment.InputXMLDocumentPanel;

import components.Phrase;

import controller.listener.SelectComponentActionListener;

public class DeleteButton extends JButton{
	public DeleteButton(){
		this.setText("Delete Selected Component");
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		double width = screenSize.getWidth();
		double height = screenSize.getHeight();
		int palettewidth = (int)(width*0.4);
		int paletteheight = (int)(height*0.1);
		Dimension dimension = new Dimension(palettewidth,paletteheight);
		this.setFont(new Font(this.getFont().getFontName(), Font.PLAIN, paletteheight/4));
		this.setPreferredSize(dimension);
		addListener();
	}

	private void addListener() {
		this.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
if(SelectComponentActionListener.getSelectedPanel()!=null){
					
					ComponentPanel selectedPanel = SelectComponentActionListener.getSelectedPanel();
					InputXMLDocumentPanel currDisplayedDocPanel = DisplayScreen.getCurrentlyDisplayedDocumentPanel();
					
					int n = JOptionPane.showConfirmDialog(
						    null,
						    "Are you sure you want to delete this component and all of its children?",
						    "Confirm",
						    JOptionPane.YES_NO_OPTION);
					if(n == JOptionPane.YES_OPTION){
						if(selectedPanel.getParentComponentPanel() != null){
							//remove internally
							Phrase parentComponent = (Phrase)selectedPanel.getParentComponentPanel().getComponent();
							parentComponent.removeChild(selectedPanel.getComponent());
							
							//remove in gui
							selectedPanel.getParentComponentPanel().removeChild(selectedPanel);
							currDisplayedDocPanel.adjustPositioning();
						}
						else{
							//remove internally
							currDisplayedDocPanel.getXMLDocument().removeSentence(selectedPanel.getComponent());
							//remove in gui
							currDisplayedDocPanel.removeChild(selectedPanel);
						}
					}
					
				}
				else{
					JOptionPane.showMessageDialog(null,
						    "No panel selected",
						    "No panel selected",
						    JOptionPane.ERROR_MESSAGE);
				}
			}
			
		});
	}
}
